package org.ktm.web.tags;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.ktm.utils.PropertyUtils;

public class MapIterateTag extends SimpleTagSupport {

    private String      id       = null;
    private String      name     = null;
    private String      property = null;

    private Map<?, ?>   table    = null;
    private Iterator<?> iterator = null;

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    @Override
    public void doTag() throws JspException, IOException {
        if (table == null) {
            try {
                Object bean = getJspContext().findAttribute(name);
                if (bean == null) { throw new JspException("no_attribute_name"); }
                if (property == null) {
                    table = (Map<?, ?>) bean;
                } else {
                    table = (Map<?, ?>) PropertyUtils.getProperty(bean, property);
                }
                if (table == null) { throw new JspException("no_map_object"); }
            } catch (Exception ex) {}
        }

        if (table instanceof Map) {
            iterator = ((Map<?, ?>) table).keySet().iterator();

            int idx = 1;
            while (iterator.hasNext()) {
                Object element = iterator.next();
                Object value = table.get(element);
                getJspContext().setAttribute(id, value);
                getJspContext().setAttribute("id", "" + idx);
                getJspBody().invoke(null);
                idx++;
            }
        }
    }

}
